package cn.iocoder.yudao.module.vote.controller.admin.voteuserresult;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;
import cn.iocoder.yudao.framework.operatelog.core.annotations.OperateLog;
import cn.iocoder.yudao.module.vote.constants.VoteModeEnum;
import cn.iocoder.yudao.module.vote.constants.VoteReviewerTypeEnum;
import cn.iocoder.yudao.module.vote.controller.admin.voterecorddetail.vo.VoteRecordCountVO;
import cn.iocoder.yudao.module.vote.controller.admin.voteuserinfo.vo.VoteUserImportExcelVO;
import cn.iocoder.yudao.module.vote.controller.admin.voteuserresult.vo.*;
import cn.iocoder.yudao.module.vote.convert.voteuserresult.VoteUserResultConvert;
import cn.iocoder.yudao.module.vote.convert.voteuserresultdetail.VoteUserResultDetailConvert;
import cn.iocoder.yudao.module.vote.dal.dataobject.dept.VoteDeptDO;
import cn.iocoder.yudao.module.vote.dal.dataobject.voteinfo.VoteInfoDO;
import cn.iocoder.yudao.module.vote.dal.dataobject.voteuserresult.VoteUserResultDO;
import cn.iocoder.yudao.module.vote.dal.dataobject.voteuserresultdetail.VoteUserResultDetailDO;
import cn.iocoder.yudao.module.vote.service.dept.VoteDeptService;
import cn.iocoder.yudao.module.vote.service.voteinfo.VoteInfoService;
import cn.iocoder.yudao.module.vote.service.voterecorddetail.VoteRecordDetailService;
import cn.iocoder.yudao.module.vote.service.voteuserresult.VoteUserResultService;
import cn.iocoder.yudao.module.vote.service.voteuserresultdetail.VoteUserResultDetailService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Collection;
import java.util.List;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.operatelog.core.enums.OperateTypeEnum.EXPORT;

@Api(tags = "管理后台 - 投票结果")
@RestController
@RequestMapping("/vote/user-result")
@Validated
public class VoteUserResultController {

    @Resource
    private VoteUserResultService userResultService;
    @Resource
    private VoteUserResultDetailService resultDetailService;
    @Resource
    private VoteInfoService voteInfoService;
    @Resource
    private VoteDeptService voteDeptService;
    @Resource
    private VoteRecordDetailService recordDetailService;

    @PostMapping("/create")
    @ApiOperation("创建投票结果")
    @PreAuthorize("@ss.hasPermission('vote:user-result:create')")
    public CommonResult<Integer> createUserResult(@Valid @RequestBody VoteUserResultCreateReqVO createReqVO) {
        return success(userResultService.createUserResult(createReqVO));
    }

    @PutMapping("/update")
    @ApiOperation("更新投票结果")
    @PreAuthorize("@ss.hasPermission('vote:user-result:update')")
    public CommonResult<Boolean> updateUserResult(@Valid @RequestBody VoteUserResultUpdateReqVO updateReqVO) {
        userResultService.updateUserResult(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @ApiOperation("删除投票结果")
    @ApiImplicitParam(name = "id", value = "编号", required = true, dataTypeClass = Integer.class)
    @PreAuthorize("@ss.hasPermission('vote:user-result:delete')")
    public CommonResult<Boolean> deleteUserResult(@RequestParam("id") Integer id) {
        userResultService.deleteUserResult(id);
        return success(true);
    }

    @GetMapping("/get")
    @ApiOperation("获得投票结果")
    @ApiImplicitParam(name = "id", value = "编号", required = true, example = "1024", dataTypeClass = Integer.class)
    @PreAuthorize("@ss.hasPermission('vote:user-result:query')")
    public CommonResult<VoteUserResultRespVO> getUserResult(@RequestParam("id") Integer id) {
        VoteUserResultDO userResult = userResultService.getUserResult(id);
        VoteUserResultRespVO resultRespVO = VoteUserResultConvert.INSTANCE.convert(userResult);

        VoteInfoDO voteInfoDO= voteInfoService.getInfo(userResult.getVoteId());
        resultRespVO.setIsQuote(voteInfoDO.getIsQuote());

        return success(resultRespVO);
    }

    @GetMapping("/list")
    @ApiOperation("获得投票结果列表")
    @ApiImplicitParam(name = "ids", value = "编号列表", required = true, example = "1024,2048", dataTypeClass = List.class)
    @PreAuthorize("@ss.hasPermission('vote:user-result:query')")
    public CommonResult<List<VoteUserResultRespVO>> getUserResultList(@RequestParam("ids") Collection<Integer> ids) {
        List<VoteUserResultDO> list = userResultService.getUserResultList(ids);
        return success(VoteUserResultConvert.INSTANCE.convertList(list));
    }

    @GetMapping("/page")
    @ApiOperation("获得投票结果分页")
    @PreAuthorize("@ss.hasPermission('vote:user-result:query')")
    public CommonResult<PageResult<VoteUserResultTechRespVO>> getUserResultPage(@Valid VoteUserResultPageReqVO pageVO) {
        PageResult<VoteUserResultDO> pageResult = userResultService.getUserResultPage(pageVO);
        PageResult<VoteUserResultTechRespVO> resultVO = VoteUserResultConvert.INSTANCE.convertTechPage(pageResult);

        for(VoteUserResultTechRespVO respVO:resultVO.getList()){
            VoteDeptDO voteDeptDO =  voteDeptService.getDept(respVO.getGroupId());

            if(voteDeptDO!=null){
                respVO.setGroupName(voteDeptDO.getName());
            }
            voteDeptDO = voteDeptService.getDept(respVO.getDeptId());
            if(voteDeptDO!=null){
                respVO.setUnitName(voteDeptDO.getName());
            }
        }
        return success(resultVO);
    }


//    private void countRecord(VoteUserResultTechRespVO respVO){
//        List<VoteRecordCountVO> mgrRecordCountList = recordDetailService.getByResultId(respVO.getVoteId(),respVO.getId(),true,false);
//        List<VoteRecordCountVO> deptRecordCountList = recordDetailService.getByResultId(respVO.getVoteId(),respVO.getId(),false,true);
//        List<VoteRecordCountVO> otherRecordCountList = recordDetailService.getByResultId(respVO.getVoteId(),respVO.getId(),false,false);
//
//        // 领导
//        if(CollUtil.isNotEmpty(mgrRecordCountList)){
//            VoteRecordCountVO countVO = mgrRecordCountList.get(0);
//            respVO.setBaseQualifiedMgr(countVO.getBaseQualifiedCount());
//            respVO.setExcellentMgr(countVO.getExcellentCount());
//            respVO.setQualifiedMgr(countVO.getQualifiedCount());
//            respVO.setUnqualifiedMgr(countVO.getUnqualifiedCount());
//        }
//        // 负责人
//        if(CollUtil.isNotEmpty(deptRecordCountList)){
//            VoteRecordCountVO countVO = deptRecordCountList.get(0);
//            respVO.setBaseQualifiedDept(countVO.getBaseQualifiedCount());
//            respVO.setExcellentDept(countVO.getExcellentCount());
//            respVO.setQualifiedDept(countVO.getQualifiedCount());
//            respVO.setUnqualifiedDept(countVO.getUnqualifiedCount());
//        }
//        // 员工
//        if(CollUtil.isNotEmpty(otherRecordCountList)){
//            VoteRecordCountVO countVO = otherRecordCountList.get(0);
//            respVO.setBaseQualifiedStaff(countVO.getBaseQualifiedCount());
//            respVO.setExcellentStaff(countVO.getExcellentCount());
//            respVO.setQualifiedStaff(countVO.getQualifiedCount());
//            respVO.setUnqualifiedStaff(countVO.getUnqualifiedCount());
//        }
//    }

    @GetMapping("/pageName")
    @ApiOperation("获得投票结果分页")
    @PreAuthorize("@ss.hasPermission('vote:user-result:query')")
    public CommonResult<PageResult<VoteUserResultNameRespVO>> getUserResultNamePage(@Valid VoteUserResultPageReqVO pageVO) {
        PageResult<VoteUserResultDO> pageResult = userResultService.getUserResultPage(pageVO);
        return success(VoteUserResultConvert.INSTANCE.convertPage2(pageResult));
    }

    @GetMapping("/export-excel")
    @ApiOperation("导出投票结果 Excel")
    @PreAuthorize("@ss.hasPermission('vote:user-result:export')")
    @OperateLog(type = EXPORT)
    public void exportUserResultExcel(@Valid VoteUserResultExportReqVO exportReqVO,
              HttpServletResponse response) throws IOException {
        List<VoteUserResultDO> list = userResultService.getUserResultList(exportReqVO);
        // 导出 Excel
        List<VoteUserResultTechRespVO> resultList = VoteUserResultConvert.INSTANCE.convertTechList(list);


        for(VoteUserResultTechRespVO techRespVO:resultList){
            if (VoteReviewerTypeEnum.TEAM_MEMBER.getValue().equals(techRespVO.getVoteReviewerType())) {
                techRespVO.setVoteReviewerTypeStr(VoteReviewerTypeEnum.TEAM_MEMBER.getRemark());
            }else if(VoteReviewerTypeEnum.TEAM_LEADER.getValue().equals(techRespVO.getVoteReviewerType())) {
                techRespVO.setVoteReviewerTypeStr(VoteReviewerTypeEnum.TEAM_LEADER.getRemark());
            }
//            VoteDeptDO voteDeptDO =  voteDeptService.getDept(techRespVO.getGroupId());
//            if(voteDeptDO!=null){
//                techRespVO.setGroupName(voteDeptDO.getName());
//            }
            VoteDeptDO voteDeptDO = voteDeptService.getDept(techRespVO.getDeptId());
            if(voteDeptDO!=null){
                techRespVO.setUnitName(voteDeptDO.getName());
            }
        }

        List<VoteUserResultExcelVO> datas = VoteUserResultConvert.INSTANCE.convertTechList02(resultList);

        ExcelUtils.write(response, "投票结果.xls", "数据", VoteUserResultExcelVO.class, datas);
    }


    @GetMapping("/get-import-template")
    @ApiOperation("获得投票用户模板")
    public void importTemplate(HttpServletResponse response) throws IOException {
        // 输出
        ExcelUtils.write(response, "投票用户导入模板.xls", "用户列表", VoteUserResultImportExcelVO.class, null);
    }

    @PostMapping("/import")
    @ApiOperation("导入投票用户信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "file", value = "Excel 文件", required = true, dataTypeClass = MultipartFile.class),
            @ApiImplicitParam(name = "updateSupport", value = "是否支持更新，默认为 false", example = "true", dataTypeClass = Boolean.class),
            @ApiImplicitParam(name = "voteId", value = "投票id", dataTypeClass = Integer.class)
    })
    @PreAuthorize("@ss.hasPermission('vote:user-result:import')")
    public CommonResult<VoteUserResultImportRespVO> importExcel(@RequestParam("file") MultipartFile file,
                                                          @RequestParam(value = "voteId", required = true) Integer voteId,
                                                          @RequestParam(value = "updateSupport", required = false, defaultValue = "false") Boolean updateSupport) throws Exception {
        List<VoteUserResultImportExcelVO> list = ExcelUtils.read(file, VoteUserResultImportExcelVO.class);
        return success(userResultService.importVoteResultUsers(list,voteId, updateSupport));
    }

    @GetMapping("syn-result")
    @ApiOperation("统计投票结果")
    @ApiImplicitParam(name = "voteId", value = "投票规则id", required = true, example = "1024", dataTypeClass = Integer.class)
    @PreAuthorize("@ss.hasPermission('vote:user-result:update')")
    public CommonResult<Boolean> synResult(@RequestParam("voteId") Integer voteId) {
        userResultService.countVoteResult(voteId);
        return success(true);
    }





}
